﻿using System;
using System.Collections.Generic;
using UnityEngine;
namespace GX
{
    internal class AssetDispatcher
    {
        Dictionary<string, HashSet<AssetDelegate>> _nameToListerners = new Dictionary<string, HashSet<AssetDelegate>>();
        public void AddListener(string name, AssetDelegate listener)
        {
            HashSet<AssetDelegate> listeners = null;
            if (!_nameToListerners.TryGetValue(name, out listeners))
            {
                listeners = PoolManager.Get<HashSet<AssetDelegate>>();
                _nameToListerners[name] = listeners;
            }
            listeners.Add(listener);
        }
        public void RemoveListener(string name, AssetDelegate listener)
        {
            HashSet<AssetDelegate> listeners = null;
            if (!_nameToListerners.TryGetValue(name, out listeners))
                return;
            listeners.Remove(listener);
            if (listeners.Count == 0)
            {
                _nameToListerners.Remove(name);
                PoolManager.Release(listeners);
            }
        }
        public void Clear(string name)
        {
            HashSet<AssetDelegate> listeners = null;
            if (!_nameToListerners.TryGetValue(name, out listeners))
                return;
            _nameToListerners.Remove(name);
            listeners.Clear();
            PoolManager.Release(listeners);
        }
        public void Invoke(IAssetInfo assetInfo, bool clearListeners)
        {
            HashSet<AssetDelegate> listeners = null;
            if (!_nameToListerners.TryGetValue(assetInfo.path, out listeners))
                return;
            var iter = listeners.GetEnumerator();
            while (iter.MoveNext())
            {
                iter.Current.Invoke(assetInfo);
            }
            if (clearListeners)
            {
                _nameToListerners.Remove(assetInfo.path);
                listeners.Clear();
                PoolManager.Release(listeners);
            }
        }
        public void GetKeys(Action<string> call)
        {
            var iter = _nameToListerners.GetEnumerator();
            while (iter.MoveNext())
            {
                call(iter.Current.Key);
            }
        }
    }
}